package com.nzd.slsharing.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nzd.slsharing.dto.PostDto;
import com.nzd.slsharing.pojo.LearningExchange;
import com.nzd.slsharing.pojo.LifeSharing;
import com.nzd.slsharing.pojo.PostSection;
import com.nzd.slsharing.pojo.User;
import com.nzd.slsharing.service.LearningExchangService;
import com.nzd.slsharing.service.LifeSharingService;
import com.nzd.slsharing.service.PostSectionService;
import com.nzd.slsharing.service.UserService;
import com.nzd.slsharing.util.Result;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

//生活分享控制器
@RestController
@RequestMapping("/api/lifeSharing")
public class LifeSharingController {
    @Resource
    private LifeSharingService lifeSharingService;
    @Resource
    private PostSectionService postSectionService;
    @Resource
    private UserService userService;
    @Resource
    private LearningExchangService learningExchangeService;



    //分页获取生活分享帖子(不带分页)
    @GetMapping("/list")
    public Result findAll(@RequestParam(required = false, defaultValue = "") String studentid) {
        QueryWrapper<LifeSharing> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("status",1);
        queryWrapper.eq("author",studentid);
        return Result.ok(lifeSharingService.list(queryWrapper));
    }

    //分页获取生活分享帖子(带分页)
    @GetMapping("/pageList")
    public Result findPage(@RequestParam(required = false, defaultValue = "1") Integer pageNum,
                           @RequestParam(required = false, defaultValue = "3") Integer pageSize,@RequestParam(required = false, defaultValue = "") String name) {

        QueryWrapper<LifeSharing> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type",1);
        queryWrapper.like("name",name);
        // 创建分页对象
        Page<LifeSharing> page = new Page<>(pageNum, pageSize);

        // 查询分页数据
        Page<LifeSharing> resultPage = lifeSharingService.page(page,queryWrapper);

        // 获取分页结果的记录列表并进行转换
        List<PostDto> list = resultPage.getRecords().stream()
                .map(item -> {
                    // 创建 PostDto 对象
                    PostDto postDto = new PostDto();
                    BeanUtils.copyProperties(item, postDto);
                    postDto.setPostId(item.getId());
                    postDto.setTitle(item.getName());
                    postDto.setPostType(item.getType());
                    postDto.setNumberLikes(item.getNumberLikes());
                    postDto.setPostImg(item.getPostImage());
                    postDto.setPostDate(item.getCreateTime());

                    // 查询对应的分类名称（可以考虑优化为批量查询）
                    PostSection postSection = postSectionService.getOne(new QueryWrapper<PostSection>().eq("type_code", item.getType()));
                    postDto.setPostName(postSection != null ? postSection.getTypeName() : null);

                    // 查询作者名称（同样可以考虑优化为批量查询）
                    User user = userService.getOne(new QueryWrapper<User>().eq("student_id", item.getAuthor()));
                    postDto.setAuthorName(user != null ? user.getUsername() : null);
                    postDto.setUserImg(user.getHeadSculpture());

                    return postDto;
                })
                .collect(Collectors.toList());

        // 将转换后的 list 设置为 resultPage 的 records
        // 如果 resultPage 只需要返回 PostDto 类型，可以通过包装一个新的 Page<PostDto> 来实现
        Page<PostDto> postDtoPage = new Page<>();
        BeanUtils.copyProperties(resultPage, postDtoPage);
        postDtoPage.setRecords(list);

        // 返回分页结果
        return Result.ok(postDtoPage);
    }


    //新增
    @PostMapping("/add")
    public Result add(@RequestBody LifeSharing lifeSharing) {
        lifeSharing.setType(1);
        lifeSharing.setCreateTime(new Date());
        lifeSharing.setStatus(1);
        lifeSharing.setNumberLikes(0);
        return Result.ok(lifeSharingService.save(lifeSharing));
    }

    //修改
    @PutMapping("/update")
    public Result update(@RequestBody LifeSharing lifeSharing) {
        //如果帖子类型代码不一样则删除后新增过去
        if(lifeSharing.getType()!=1){
            //对象复制
            LearningExchange learningExchange=new LearningExchange();
            BeanUtils.copyProperties(lifeSharing, learningExchange);
            learningExchange.setStatus(1);
            learningExchangeService.save(learningExchange);

        }
        lifeSharing.setUpdateTime(new Date());
        return Result.ok(lifeSharingService.updateById(lifeSharing));
    }


}
